<?php
namespace app\order\controller;

use app\classes\model\AuditionModel;
use app\classes\model\ClassModel;
use app\classes\model\ClassSeatModel;
use app\classes\model\ClassStudentModel;
use app\course\model\CourseCategoryModel;
use app\course\model\CourseModel;
use app\course\model\CoursesCartModel;
use app\financial\model\AwardCardModel;
use app\financial\model\DiscountModel;
use app\financial\model\HelpAwardModel;
use app\financial\model\OrderModel;
use app\order\service\OrderService;
use app\portal\model\UserModel;
use app\student\model\StudentModel;
use app\system\model\SchoolModel;
use cmf\controller\HomeBaseController;
use think\Db;
use think\Exception;


class OrderController extends HomeBaseController
{
    public function  index()
    {
        $p_id = cmf_get_current_admin_id();
        //判断是否有详细的信息,通过判断的家长的手机号
        $student_model = new StudentModel();

        $this->redirect('select_lesson');
    }

    public function add_student()
    {
        $id = $this->request->param('id');
        $p_id = cmf_get_current_user_id();
        $redirect = $this->request->server('HTTP_REFERER');
        $user_model = new UserModel();
        $p_id_data = $user_model->where('id', $p_id)->find();


        $school_model = new SchoolModel();
        $school_data = $school_model->where(['is_school' => 0, 'delete_time' => 0])->select()->toArray();
        if (empty($id)) {
            $id = 0;
        }
        $this->assign('id', $id);
        $this->assign('school_data', $school_data);
        $this->assign('redirect', $redirect);

        $this->assign('p_id_data', $p_id_data);

        return $this->fetch();
    }

    public function add_student_post()
    {
        if ($this->request->isPost()) {
            $model = new StudentModel();
            $p_id = cmf_get_current_user_id();
            $user_model=Db::name('user')->where(['id'=>$p_id])->find();

            $mobile=$user_model['mobile'];
            $user_email=$user_model['user_email'];
            $parent_name=$user_model['realname'];

            $post = $this->request->post();
            $data = $this->request->post();
            $information_sources_type=$data['information_sources_type'];
            if(count($information_sources_type)<1)
            {
                $this->error('没有选择信息来源');
            }

            $information_sources_type=implode(',',$information_sources_type);
            $data['information_sources_type']=$information_sources_type;
            $name=$post['name'];
            $user_login=$this->request->post('user_login'); //如果不存在 disable input 其实realrealname user表中
            $zipcode=$this->request->post('zipcode'); //如果不存在 disable input 其实realrealname user表中
            $address=$this->request->post('address'); //如果不存在 disable input 其实realrealname user表中


            $redirect = $this->request->post("redirect");
            $school_name = $this ->request->post('school_name');

            if (empty($redirect)) {
                $redirect = $this->request->server('HTTP_REFERER');
            } else {
//                $redirect = base64_decode($redirect);
            }
            session('login_http_referer', $redirect);
            $session_login_http_referer = session('login_http_referer');
            $redirect  = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;

            if(isset($user_login))
            {
                if(empty($user_login) || is_numeric($user_login))
                {
                    $this->error('家长名字不能为为空且不能是数字');
                }
            }else{
                $user_login='';
            }

            if(isset($zipcode))
            {
                if(empty($zipcode))
                {
                    $this->error('家长邮编为空');
                }
            }else{
                $zipcode='';
            }
            if(isset($address))
            {
                if(empty($address))
                {
                    $this->error('家长地址不能为空');
                }
            }else{
                $address='';
            }


            if(empty($name) || is_numeric($name))
            {
                $this->error('学生名字不能为数字');
            }
            if(empty($school_name))
            {
                $this->error('请输入孩子的学校名称');
            }

            $total = $model
                ->where('delete_time', '=', 0)
                ->where(['name' => trim($data['name'])])
                ->where(['u_id' => $p_id])
                ->count();

            if (isset($total) && $total >= 1) {
                $this->error('该学生已存在');
            }

//            if (!preg_match('/^1[3,4,5,8,7][0-9]{9}$/',$post['mobile'])){
//                $this->error('手机格式不正确');
//            }

            $result = $this->validate($post, 'Student');
            if ($result !== true) {
                $this->error($result);
            }
            if (!empty($data['birthday'])) {
                //生日
                $data['birthday'] = strtotime($data['birthday']);
            }

            //学号

            $data['code'] = $model->generateCode();
            $p_id = cmf_get_current_user_id();
            if (empty($p_id)) {
                $this->redirect('user/login/index');
            }

            $data['u_id'] = $p_id;
            $data['mobile'] = $mobile;
            $data['email'] = $user_email;
            $data['parent_name'] = $parent_name;


            $data['create_time'] = time();
            if(isset($data['class_id']))
            {
                unset($data['class_id']);
            }
            unset($data['user_login']);
            unset($data['zipcode']);
            unset($data['address']);

            unset($data['redirect']);

            $p_id = cmf_get_current_user_id();
            $id = $model->insertGetId($data); //添加学生
            if(!empty($user_login)) //不存在父母用的名字了
            {
                //载入拼音转换类
                import('ChinesePinyin.ChinesePinyin', EXTEND_PATH);

                //汉子转换为拼音
                $realname = trim($user_login);
                $pinyin_mdl = new \ChinesePinyin();
                $user_pinyin = $pinyin_mdl->TransformWithoutTone($realname,'',false);
                $user_short_pinyin = $pinyin_mdl->TransformUcwords($realname);


                //保存家长
                $user_data = [
                    'realname' => $realname,
                    'zipcode'=>$zipcode,
                    'address'=>$address,
                    'pinyin' => $user_pinyin,
                    'short_pinyin' => $user_short_pinyin,
                    'user_status1'=>2,
                ];
                Db::name('user')->where(['id'=>$p_id])->update($user_data);
            }


            $pk = $id; //主键
            $table = 'student';//数据表名


            if ($id) {
                $this->success('添加成功', $redirect);//TODO::
            } else {
                $this->error("添加失败");
            }
        }

    }

    public function select_lesson()
    {
        $param = $this->request->param();
        $couser_model = new CourseModel();
        $cousecate_model = new CourseCategoryModel();
        $shop_id = $this->front_shop_id; //这个获取不到shop_id
        $p_id = cmf_get_current_user_id();

        if(empty($shop_id)){
            $shop_id=1;
        }
        $where = [];
        if (!empty($param['category_id'])) {
            $where['cc.id'] = $param['category_id'];
        }
        //课程的分类
        $course_categroy = $cousecate_model->alias('cc')->field('cc.*')
            ->where(['cc.delete_time' => 0])
            ->order("cc.id")
            ->select();
        //所有的课程
        $data = $couser_model->alias('c')->field('c.*,a.file_path')
            ->join('course_category cc', 'cc.id=c.category_id')
            ->join('asset a', 'a.id=c.asset_id',$type='left') //图片上传
//            ->join('class cl','cl.course_id=c.id',$type='left')
            ->where($where)
            ->where(['c.delete_time' => 0, 'cc.delete_time' => 0, 'c.enabled' => 1])
//            ->where(['cl.is_and_class' => 0, 'cl.visible_type' => 0])
//            ->where('cl.class_status', ['eq', 0], ['eq', 1], 'or')
            ->order("c.id")
            ->paginate(6);
        foreach ($data as &$x) {
            $x['description'] = html_entity_decode($x['description']);
        }
        $this->assign('course_categroy', $course_categroy);
        $this->assign('data', $data);
        $this->assign('page', $data->render());

        return $this->fetch();
    }

    /*
     * 此课程下的班级
     *
     */

    public function select_ban()
    {
        $param = $this->request->param();
        $course_id = $param['course_id'];
        $school_id = $this->request->param('school_id', '0');
        $shop_id = $this->front_shop_id; //这个获取不到shop_id
        if(empty($shop_id)){
            $shop_id=1;
        }
        $class_model = new ClassModel();
        $course_model = new CourseModel();
        $school_model = new SchoolModel();

        /*
         * 如果数据为is_null，那么着呢名此课程还没有开班呢
         * visible_type是全部可见
         * is_and_class=0是没有并班，就是此班级还存在
         * class_stauts 0:没有开课的班级，1：进行中的班级
         */
        $class_ids = $class_model
            ->where(['course_id' => $course_id, 'is_and_class' => 0, 'visible_type' => 0])
            ->where('class_status', ['eq', 0], ['eq', 1], 'or')->select();
        if (isset($class_ids) && empty($class_ids->toArray())) {
            $this->redirect('pre_class', array('course_id' => $course_id));
        }

        //查看当前用户是否是预选家长
        $p_id = cmf_get_current_user_id();
        $pre_count = Db::name('primary_parent')->where(['delete_time' => 0, 'use_id' => $p_id, 'course_id' => $course_id, 'shop_id' => $shop_id])->count();
        $pre_create_time = Db::name('primary_parent')->where(['delete_time' => 0, 'use_id' => $p_id, 'course_id' => $course_id])->value('create_time');
        //家长选择课程，时间超过一年
        if ($pre_create_time + 365 * 24 * 3600 < time()) {
            $pre_count = 0;
        }

        //查看是否在籍家长或者非在籍家长
        $is_pre=Db::name('order')->where([ 'parent_id' => $p_id, 'shop_id' => $shop_id])
            ->where('order_status', ['eq', 2], ['eq', 1], 'or')
            ->count();



        //查看仅仅是原来的续报可见(续报）
        //初始化
        $n = 0;
        foreach ($class_ids as $k => $v) {
            if ($v['total_num'] <= $v['current_num']) {
                $n += 1;
            }
        }
        if (!empty($class_ids) && empty($pre_count)) {
            if (count($class_ids->toArray()) == $n) {
                //满员跳到预选课页面
                $this->redirect('pre_class', array('course_id' => $course_id));
            }
        }
    //如果存在预选课的session,清空
        if(isset($_SESSION['student_status']) && !empty($_SESSION['student_status']))
        {
            unset($_SESSION['student_status']);
        }
        $where = [];
        if (!empty($param['school_id'])) {
            $where['s.id'] = $param['school_id'];
        } else {
            //默认是第一校区
            $s_id = $school_model->where(['delete_time' => 0, 'shop_id' => $shop_id,'is_school' => 0])->order('id asc')->limit(1)->value('id');
            $where['s.id'] = $s_id;
            $school_id=$s_id;
        }

        /*
         * 课程简介      /学悦教育 - 课程体系 - 测试预选课1
         * 没有图片没有让left join
         */
        $course_name = $course_model->alias('c')->field('c.*,a.file_path')
            ->join('course_category cc', 'cc.id=c.category_id')
            ->join('asset a', 'a.id=c.asset_id',$type='left')
            ->where(['c.delete_time' => 0, 'cc.delete_time' => 0, 'c.id' => $course_id])
            ->find();
        foreach ($course_name as &$x) {
            $x['description'] = html_entity_decode($x['description']);
        }

        /*
         * 此课程下的班级，没有结课，没有并班,没有删除
         * 分页为4个
         * 已开课时间
         * 可见范围 0 1 2 3
         */

        $data = $class_model->alias('cm')->field('cm.*,c.course_name,s.address,u.user_login')
            ->join('course c', 'cm.course_id=c.id')
            ->join('school s', 's.id=cm.school_id')
            ->join('user u', 'u.id=cm.teacher_id')
            ->where(['cm.course_id' => $course_id, 'cm.is_and_class' => 0, 'cm.delete_time' => 0, 'cm.shop_id' => $shop_id])
            ->where('cm.class_status', '<>', '2')
            ->where($where)
            ->order('cm.start_lesson_time','asc')
//            ->buildSql();
//            dump($data);
        ->paginate(4);

        foreach ($data as $k => $v) {
            $where = [
                'class_id' => ['=', $v['id']],
                'teacher_id' => ['=', $v['teacher_id']],
                'schedule' => ['<>', 0],
            ];
            //获取排课列表，并且排序
            $date = Db::name('course_schedule')->where($where)->order('date', 'asc')->select();
            $date = $date->toArray();
            sort($date);
            $len = count($date);
            if ($len < 0) {
                $this->error('此课程没有排课，请耐心等待 ');
            }

            //判断第一个是否存在
            if (!empty($date[0]['date'])) {
                $first_day = date("Y.m.d", $date[0]['date']);
                $end_day = date("Y.m.d", $date[$len - 1]['date']);
                $data[$k]['first_day'] = $first_day;
                $data[$k]['end_day'] = $end_day;
            } else {
                $data[$k]['first_day'] = '2017-10-1';
                $data[$k]['end_day'] = '2018-10-1';
            }
            //凭借多个上课时间段
            $class_start_week = explode(',', $v['class_start_week']);
            $class_time_start = explode(',', $v['class_time_start']);
            $class_time_end = explode(',', $v['class_time_end']);
            $data[$k]['class_start_week'] = '';

            foreach ($class_start_week as $j => $v) {
                if ($class_time_start[$j] <= 13) {
                    $ww = '上午';
                } else {
                    $ww = '下午';
                }

                switch ($class_start_week[$j]) {
                    case 6:
                        $class_week = '星期六';
                        break;
                    case 7:
                        $class_week = '星期日';
                        break;
                    case 5:
                        $class_week = '星期五';
                        break;
                    case 4:
                        $class_week = '星期四';
                        break;
                    case 3:
                        $class_week = '星期三';
                        break;
                    case 2:
                        $class_week = '星期二';
                        break;
                    default:
                        $class_week = '星期一';
                }
                $data[$k]['class_start_week'] .= $class_week . $ww . $class_time_start[$j] . "-" . $class_time_end[$j];

            }
        }
        /*
         *校区的选择，点击校区，如果没有选择校区，默认是第一个校区
         */
        //没有登录的话,$shop_id=1默认为1
        $userId = cmf_get_current_user_id();
        if(empty($userId))
        {
            $shop_id=1;
        }
        $school_date = $school_model->where(['delete_time' => 0, 'is_school' => 0, 'shop_id' => $shop_id])->order("id")
            ->limit(6)
            ->select()
            ->toArray();
        //课程内容

        $course_date=Db::name('course')->where(['id'=>$course_id])->find();
        $course_date['description'] = html_entity_decode($course_date['description']);
        $this->assign('course_date', $course_date);
        $this->assign('pre_count', $pre_count);
        $this->assign('data', $data);
        $this->assign('course_id', $course_id);
        $this->assign('school_id', $school_id);
        $this->assign('school_date', $school_date);
        $this->assign('course_name', $course_name);
        $this->assign('page', $data->render());
        return $this->fetch();

    }

    /*
     * 此课程下的班级(异步)
     *
     */

    public function ajax_select_ban()
    {
        $param = $this->request->param();
        $course_id = $param['course_id'];
        $school_id = $this->request->param('school_id', '0');
        $shop_id = $this->front_shop_id; //这个获取不到shop_id
        if(empty($shop_id)){
            $shop_id=1;
        }
        $class_model = new ClassModel();
        $course_model = new CourseModel();
        $school_model = new SchoolModel();

        /*
         * 如果数据为is_null，那么着呢名此课程还没有开班呢
         * visible_type是全部可见
         * is_and_class=0是没有并班，就是此班级还存在
         * class_stauts 0:没有开课的班级，1：进行中的班级
         */
        $class_ids = $class_model
            ->where(['course_id' => $course_id, 'is_and_class' => 0, 'visible_type' => 0])
            ->where('class_status', ['eq', 0], ['eq', 1], 'or')->select();
        if (isset($class_ids) && empty($class_ids->toArray())) {
            $this->redirect('pre_class', array('course_id' => $course_id));
        }

        //查看当前用户是否是预选家长
        $p_id = cmf_get_current_user_id();
        $pre_count = Db::name('primary_parent')->where(['delete_time' => 0, 'use_id' => $p_id, 'course_id' => $course_id, 'shop_id' => $shop_id])->count();
        $pre_create_time = Db::name('primary_parent')->where(['delete_time' => 0, 'use_id' => $p_id, 'course_id' => $course_id])->value('create_time');
        //家长选择课程，时间超过一年
        if ($pre_create_time + 365 * 24 * 3600 < time()) {
            $pre_count = 0;
        }

        //查看是否在籍家长或者非在籍家长
        $is_pre=Db::name('order')->where([ 'parent_id' => $p_id, 'shop_id' => $shop_id])
            ->where('order_status', ['eq', 2], ['eq', 1], 'or')
            ->count();



        //查看仅仅是原来的续报可见(续报）
        //初始化
        $n = 0;
        foreach ($class_ids as $k => $v) {
            if ($v['total_num'] <= $v['current_num']) {
                $n += 1;
            }
        }
        if (!empty($class_ids) && empty($pre_count)) {
            if (count($class_ids->toArray()) == $n) {
                //满员跳到预选课页面
                $this->redirect('pre_class', array('course_id' => $course_id));
            }
        }
        //如果存在预选课的session,清空
        if(isset($_SESSION['student_status']) && !empty($_SESSION['student_status']))
        {
            unset($_SESSION['student_status']);
        }
        $where = [];
        if (!empty($param['school_id'])) {
            $where['s.id'] = $param['school_id'];
        } else {
            //默认是第一校区
            $s_id = $school_model->where(['delete_time' => 0, 'shop_id' => $shop_id,'is_school' => 0])->order('id asc')->limit(1)->value('id');
            $where['s.id'] = $s_id;
            $school_id=$s_id;
        }

        /*
         * 此课程下的班级，没有结课，没有并班,没有删除
         * 分页为4个
         * 已开课时间
         * 可见范围 0 1 2 3
         */

        $data = $class_model->alias('cm')->field('cm.*,c.course_name,s.address,u.user_login')
            ->join('course c', 'cm.course_id=c.id')
            ->join('school s', 's.id=cm.school_id')
            ->join('user u', 'u.id=cm.teacher_id')
            ->where(['cm.course_id' => $course_id, 'cm.is_and_class' => 0, 'cm.delete_time' => 0, 'cm.shop_id' => $shop_id])
            ->where('cm.class_status', '<>', '2')
            ->where($where)
            ->order('cm.start_lesson_time','asc')
//            ->buildSql();
//            dump($data);
            ->paginate(4);

        foreach ($data as $k => $v) {
            $where = [
                'class_id' => ['=', $v['id']],
                'teacher_id' => ['=', $v['teacher_id']],
                'schedule' => ['<>', 0],
            ];
            //获取排课列表，并且排序
            $date = Db::name('course_schedule')->where($where)->order('date', 'asc')->select();
            $date = $date->toArray();
            sort($date);
            $len = count($date);
            if ($len < 0) {
                $this->error('此课程没有排课，请耐心等待 ');
            }

            //判断第一个是否存在
            if (!empty($date[0]['date'])) {
                $first_day = date("Y.m.d", $date[0]['date']);
                $end_day = date("Y.m.d", $date[$len - 1]['date']);
                $data[$k]['first_day'] = $first_day;
                $data[$k]['end_day'] = $end_day;
            } else {
                $data[$k]['first_day'] = '2017-10-1';
                $data[$k]['end_day'] = '2018-10-1';
            }
            //凭借多个上课时间段
            $class_start_week = explode(',', $v['class_start_week']);
            $class_time_start = explode(',', $v['class_time_start']);
            $class_time_end = explode(',', $v['class_time_end']);
            $data[$k]['class_start_week'] = '';

            foreach ($class_start_week as $j => $v) {
                if ($class_time_start[$j] <= 13) {
                    $ww = '上午';
                } else {
                    $ww = '下午';
                }

                switch ($class_start_week[$j]) {
                    case 6:
                        $class_week = '星期六';
                        break;
                    case 7:
                        $class_week = '星期日';
                        break;
                    case 5:
                        $class_week = '星期五';
                        break;
                    case 4:
                        $class_week = '星期四';
                        break;
                    case 3:
                        $class_week = '星期三';
                        break;
                    case 2:
                        $class_week = '星期二';
                        break;
                    default:
                        $class_week = '星期一';
                }
                $data[$k]['class_start_week'] .= $class_week . $ww . $class_time_start[$j] . "-" . $class_time_end[$j];

            }
        }
        /*
         *校区的选择，点击校区，如果没有选择校区，默认是第一个校区
         */
        //没有登录的话,$shop_id=1默认为1
        $userId = cmf_get_current_user_id();
        if(empty($userId))
        {
            $shop_id=1;
        }
        $school_date = $school_model->where(['delete_time' => 0, 'is_school' => 0, 'shop_id' => $shop_id])->order("id")
            ->limit(6)
            ->select()
            ->toArray();
        //课程内容
        $this->assign('pre_count', $pre_count);
        $this->assign('data', $data);
        $this->assign('course_id', $course_id);
        $this->assign('school_id', $school_id);
        $this->assign('school_date', $school_date);
        $this->assign('page', $data->render());
        return $this->fetch();

    }

    /*
     * 预选课程页面
     */
    public function pre_class()
    {

        $course_id = $this->request->param('course_id');
        $shop_id = $this->front_shop_id;
        $course_data = Db::name('course')->where(['id' => $course_id, 'delete_time' => 0, 'shop_id' => $shop_id])->find();

        $school_data = Db::name('school')->where(['delete_time' => 0, 'shop_id' => $shop_id])->select()->toArray();

        /*
        $school_data = Db::name('class')->alias('c')->distinct('s.id')->field('s.id sid,s.name sname')
                   ->join('course cc','cc.id=c.course_id')
                   ->join('school s','s.id=c.school_id')
            ->where(['s.delete_time' => 0, 's.is_school' => 0,'c.course_id' =>$course_id,'c.shop_id' => $shop_id])->select()->toArray();
        */
        $this->assign('course_id', $course_id);
        $this->assign('course_data', $course_data);
        $this->assign('school_data', $school_data);
        return $this->fetch();
    }

    /*
     * 预选课程post存到数据库
     */
    public function pre_class_post()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $p_id = cmf_get_current_user_id();
            $course_id = $this->request->param('course_id');


            if (empty($post['school_id'])) {
                $this->error('没有选择校区');
            }
            $data = [];
            $data['course_id'] = $course_id;
            $data['school_id'] = $post['school_id'];
            $data['use_id'] = $p_id;
            $data['create_time'] = time();
            $data['shop_id'] = 1;
            Db::startTrans();
            try {
                Db::name('primary_parent')->insert($data);
                Db::commit();

                $this->success('恭喜你,完成预选课报名,开课的时间提前通知您', url('order/select_lesson'));

            } catch (Exception $e) {
                $this->error('没有完成预选课报名');
                Db::rollback();

            }
        }
    }

    public function select_class()
    {

        //当前的用户没有登录，去登录
        $p_id = cmf_get_current_user_id();
        $cha_id=$this->request->param('cha_id',0);

        if (empty($p_id)) {
            $this->redirect('user/login/index');
        }

        $student_id = $this->request->param('student_id');
        $cid = $this->request->param('id');

        $p_id = cmf_get_current_user_id();
        $param = $this->request->param();

        $class_model = new ClassModel();
        $data = $class_model->alias('c')->field('c.*')
            ->where(['c.delete_time' => 0, 'c.id' => $cid])
            ->where('c.start_lesson_time', 'gt', time())
            ->order("c.id")
            ->paginate(10);

        $order_model = new OrderModel();
        $order_count = $order_model->where(['parent_id' => $p_id, 'order_status' => 0])->count();
        if ($order_count > 1) {
            $this->error('你还有没有支付的订单呢');
        }

        //chase添加查询座位信息;
        //$cid应为传输过来的班级id;
        //查询班级对应教室,家长座位,过道,排列;
        $seat_data = $class_model->alias('c')->where('c.id', $cid)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats')
            ->where('classes_id', $cid)
            ->where('delete_time',0)
            ->select()
            ->toArray();

        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }


        $this->assign('seat_data', $seat_data);
        //chase添加查询座位信息end;


        $this->assign('data', $data);

        $this->assign('id', $cid);
        $this->assign('student_id', $student_id);

        return $this->fetch();
    }

    /*
     * ajax 的选择学生
     * 产生牛牛卡或者奖学金
     */
    public function ajax_student()
    {
        //奖学金/牛牛卡
        $award_card = new AwardCardModel();
        $award_order_id = Db::name('award_order')->column('award_student_id');
        //如果是一个的话，就不是数组
        if(!is_array($award_order_id))
        {
            $award_order_id[]=$award_order_id;
        }
        $student_id = $this->request->param('student_id','0');
        $p_id = cmf_get_current_user_id();

        $award_card_data = $award_card->alias('d')
            ->join('award_student aw', 'aw.award_id=d.id')
            ->where(['d.delete_time' => 0, 'aw.student_id' => $student_id])
            ->whereOr([ 'aw.u_id' => $p_id])
//            ->buildSql();
            ->select();

        //whereor的话就会and and or  想要的是  and (and or)
        if(!$award_card_data->isEmpty())
        {
            $award_card_data=$award_card_data->toArray();
            $j='';
            foreach($award_card_data as $k=>$v)
            {
                if(count($award_card_data)<1)
                {
                    $award_card_data=[];
                }
                if(in_array($v['award_id'],$award_order_id))
                {
                    unset($award_card_data[$k]);
                }
            }
        }else{
            $award_card_data=[];
        }
        if(count($award_card_data)==1)
        {
            return json_encode($award_card_data);

        }
        return json_encode($award_card_data);
    }

    /*
     * ajax 的选择学生
     * 产生助学金
     */
    public function ajax_help_awrard()
    {
        //助学金
        $student_id = $this->request->param('student_id');

        $help_awrad = new HelpAwardModel();
        $help_awrad_data = $help_awrad->alias('ha')->field('ha.id,ha.money,ha.type,ha.award_id')
            ->join('help_award_money h', 'ha.award_id=h.id')
            ->where(['ha.student_id' => $student_id, 'ha.status' => 2,'ha.delete_time'=>0])->find();
        if (!isset($help_awrad_data['money'])) {
            $help_awrad_data = [];
        }

        //看看是不是老学生
        $class_student_model=new StudentModel();
         $is_old_student=$class_student_model->where(['id'=>$student_id])->value('is_old_student'); //看看是不是老学生 报名费
        if (!empty($is_old_student)) {
            $help_awrad_data['oldstudent'] = 1;
        } else {
            $help_awrad_data['oldstudent'] = 0;
        }
        return json_encode($help_awrad_data);

    }


    public function order_list()
    {
        //班级id

        //当前用户的id
        $p_id = cmf_get_current_user_id();
        //当前的用户没有登录，去登录
        if (empty($p_id)) {
            $this->redirect('user/login/index');
        }
        $id = $this->request->param('class_id');
        $student_id = $this->request->param('student_id');
        //是否插板的学生
        $cha_id = $this->request->param('cha_id',0);
        //清空session['student_statusss']
        //如果存在预选课的session,清空
        $student_status= $this->request->param('student_status',0);
        if(isset($_SESSION['student_status']) && !empty($_SESSION['student_status']))
        {
            unset($_SESSION['student_status']);
        }
        if(isset($_SESSION['student_status1']) && !empty($_SESSION['student_status1']))
        {
            unset($_SESSION['student_status1']);
        }

        //续班的原班级，统计分析用
        if(isset($_SESSION['class_id']) && !empty($_SESSION['class_id']))
        {
            unset($_SESSION['class_id']);
        }


        $order_model = new OrderModel();
        $class_model = new ClassModel();
        $course_model = new CourseModel();
        $student_model = new StudentModel();
        $user_model=new UserModel();
        $discount = new DiscountModel();
        $class_student=new ClassStudentModel();

        //如果连续生成两次订单，生成第三次的时候先去支付或者取消订单
        $order_count = $order_model->where(['parent_id' => $p_id, 'order_status' => 0])->count();
        if ($order_count > 1) {
            $this->error('你还有没有支付的订单呢', url('order/front_order/index'));
        }



        //家长的学生信息
        $student_data = $student_model->where(['u_id' => $p_id,'delete_time'=>0])->select();
        $count=$student_data->count();
        //没有学生信息，去填写学生信息
        if (empty($count)) {
            $this->redirect('order/add_student', array('id' => $id));
        } else {
            $student_data = $student_data->toArray();
        }

        //优惠活动
        $discount_data = $discount->where(['delete_time' => 0])->select();
        $discount_data_count=$discount_data->count();
        if (empty($discount_data_count)) {
            $discount_data = $discount_data->toArray();
        }
        //班级详情
        $data = $class_model->where(['id' => $id])->find();

        //上课的时间
        //凭借多个上课时间段
        $class_start_week = explode(',', $data['class_start_week']);
        $class_time_start = explode(',', $data['class_time_start']);
        $class_time_end = explode(',', $data['class_time_end']);
        $data['class_start_week'] = '';

        foreach ($class_start_week as $j => $v) {
            if ($class_time_start[$j] <= 13) {
                $ww = '上午';
            } else {
                $ww = '下午';
            }

            switch ($class_start_week[$j]) {
                case 6:
                    $class_week = '星期六';
                    break;
                case 7:
                    $class_week = '星期日';
                    break;
                case 5:
                    $class_week = '星期五';
                    break;
                case 4:
                    $class_week = '星期四';
                    break;
                case 3:
                    $class_week = '星期三';
                    break;
                case 2:
                    $class_week = '星期二';
                    break;
                default:
                    $class_week = '星期一';
            }
            $data['class_start_week'] .= $class_week . $ww . $class_time_start[$j] . "-" . $class_time_end[$j] ."  ";

        }

            //判断这个班级和这个课程是否能够连报二年，最多就是三年
        $enable_class = $this->enable_class($id);
        //查看课时
        //查看课时             //排课表
        $lesson_schema=Db::name('course_schedule')->where(['class_id'=>$id])->order('date','asc')->select();
        if($lesson_schema->isEmpty())
        { //课时为空的情况
            $this->error('课时情况正在调整');
        }
        $lesson_schema = $lesson_schema->toArray(); //转化数据
        sortArrByField($lesson_schema,'date',$asc = true); //时间排序（防止加课）正序
        $last=count($lesson_schema); //取得最后一个课时日期

        if (empty($lesson_schema[0]['date'])) {
            //排课表第一节课为空
            $this->error('第一节课不存在');
        }

        //课程的course表，判断是否有1,2，3年连报优惠
        $course_id = $class_model->where('id', $id)->value('course_id');
        $length = $course_model->where('id', $course_id)->value('course_hour');
        $course_data = $course_model->where('id', $course_id)->find();
        if (!isset($course_data['one_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        if (!isset($course_data['two_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        if (!isset($course_data['three_reduce_price'])) {
            $course_data['one_reduce_price'] = 0;
        }
        //插板过来的学生 ，算课时
        if (!empty($cha_id)) {
            $cur_time = time();
            foreach ($lesson_schema as $k => $v) { //找出课时
                if (!empty($lesson_schema[$k + 1]['date'])) { //一般都是存在的2课时以上的
                    if ($cur_time > $lesson_schema[$k]['date'] && $cur_time < $lesson_schema[$k + 1]['date']) {
                        $progress = $lesson_schema[$k]['schedule']; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } elseif ($cur_time < $lesson_schema[0]['date']) { //小于开课时间
                        $progress = 0; //当前课时
                        $progress_sheng = $length - $progress; //剩余课时
                    } else if ($cur_time > $lesson_schema[$last - 1]['date']) {  //已经结课
                        $progress = $length; //当前课时
                        $progress_sheng = 0; //剩余课时
                    }
                }
            }
            $data['progress']=$progress;
            $data['progress_sheng']=$progress_sheng;
            $data['total_progress']=$last;

        }else{
            $data['progress']=$last;
            $data['progress_sheng']=0;
            $data['total_progress']=$last;
        }





        $order_model = new OrderModel();
        $order_count = $order_model->where(['parent_id' => $p_id, 'order_status' => 0])->count();
        if ($order_count >1) { //存在两个订单
            $this->error('你还有没有支付的订单呢');
//            $this->redirect('');
        }

        //chase添加查询座位信息;
        //$cid应为传输过来的班级id;
        //查询班级对应教室,家长座位,过道,排列;
        $seat_data = $class_model->alias('c')->where('c.id', $id)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats')
            ->where('classes_id', $id)
            ->where('delete_time',0)
            ->select()
            ->toArray();

        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }


        $this->assign('seat_data', $seat_data);
        //chase添加查询座位信息end;


        //查询用户注册信息时候填写的地址作为默认发票地址
        $address=$user_model->where('id',$p_id)->value('address');
        $this->assign('data', $data);
        $this->assign('student_data', $student_data);
        $this->assign('student_id', $student_id);
        $this->assign('course_data', $course_data);
        $this->assign('cha_id', $cha_id);
        $this->assign('enable_class', $enable_class);
        $this->assign('address',$address);
        return $this->fetch();
    }


    public function  preview_seat()
    {
        $cid = $this->request->param('class_id');
        $class_model = new ClassModel();

        //$cid应为传输过来的班级id;
        //查询班级对应教室,家长座位,过道,排列;
        $seat_data = $class_model->alias('c')->where('c.id', $cid)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats')
            ->where('classes_id', $cid)
            ->where('delete_time',0)
            ->select()
            ->toArray();

        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }


        return json_encode($seat_data);
    }


    /*
     * 递归一个函数连报,首先判断连报的课程的 is_class enable_class_ids
    */
    public function enable_class($class_id, $data = [])
    {
        $class_data = Db::name('class')->where(['id' => $class_id])->find();
        $is_class = $class_data['is_class'];
        $enable_class = $class_data['enable_class_ids'];
        if (!empty($is_class)) {
            if (!empty($enable_class)) {
                $class_id = intval(explode(',', $enable_class)[0]);
                $data[] = $class_id;
                $data = array_merge($data, $this->enable_class($class_id));
            }else{
                return $data;
            }
        }
        return $data;
    }

    public   function   product_order()
    {

        //非法登录操作
        $this->checkUserLogin();
        if ($this->request->isPost()) {

            $post = $this->request->post();
            $class_id = $post['class_id'];       //班级id
            $student_id = $post['student_id'];
            $cha_id = $this->request->param('cha_id','0');     //是否插板
            $post['cha_id']=$cha_id;

            //判断学生是否在此班级占座了
            $class_seat_model = new ClassSeatModel();
            $student_seat = $class_seat_model->where(['classes_id' => $class_id, 'student_id' => $student_id, 'delete_time' => 0])->find();
            if (!empty($student_seat)) {
                $this->error('您在此班级已经报过名了!!!');
            }
            if (empty($student_id)) {
                //选择学生为空
                $this->error('请选择孩子');
            }
            if (empty($post['student_seat'])) {
                $this->error('请至少选择一个座位');
            }
            //注意并发性
            $file = fopen(__DIR__ . '/2.html.lock', "w+");

            // 排它性的锁定
            if (flock($file, LOCK_EX)) {
                fwrite($file, "Write something");
                $count = $class_seat_model->where(['classes_id' => $class_id, 'student_seat' => $student_seat])->find();

                if (!is_null($count)) {
                    flock($file, LOCK_UN);
                    $this->error('座位已经占了');
                }
                // release lock
                flock($file, LOCK_UN);
            } else {
                echo "Error locking file!";
            }

            $class_model=new ClassModel();
            $class_student=new ClassStudentModel();
            //如果学生在统一课程下，2个月连续报班2次以上就报错，就停止报班
            $course_id = $class_model->where('id', $class_id)->value('course_id');
            $first_data=$class_student->field('insert_class_time')
                ->where(['student_id'=>$student_id,'course_id'=>$course_id,'delete_time'=>0])
                ->order('insert_class_time', 'asc')->select();

            if(!$first_data->isEmpty())
            {
                $first_data=$first_data->toArray();
                if(count($first_data)>1)
                {
                    $first_time=$first_data[0]['insert_class_time'];
                    if($first_time+60*24*3600>time())
                    {
                        $this->error('两个月内同课程最多报名两次');
                    }
                }

            }


            $orderService=new OrderService();
            $code=$orderService->product_order($post);
            $order_data=Db::name('order')->where('id',$code)->find();
            $order_id=$order_data['order_id'];
            $payment=$order_data['payment'];
            if($payment==0)
            {
                $this->success('选座成功', url('user/user/profile'));
            }
            if($order_id){
                $this->success('选座成功', url('FrontOrder/orderPay', array('order_id' => base64_encode($order_id), 'student_id' => $student_id)));
            }else{
                $this->error('选座失败');
            }

        }
    }

    /**
     *用户登录，没有登录的话，就返回登录
     */
    public function checkUserLogin()
    {
        $userId = cmf_get_current_user_id();
        if (empty($userId)) {
            $this->error("用户尚未登录", url("user/login/index"));
        }
    }
    /*
     * 试听
     */
    public function isListen()
    {
        $param = $this->request->param();
        $class_id = $param['class_id'];       //班级id
        $student_status = $param['student_status']; //状态 7 位试听
        $isListen = $param['is_listen'];          //插板
        $order_model = new OrderModel();
        $class_model = new ClassModel();
        $course_model = new CourseModel();
        $student_model = new StudentModel();
        $user_model=new UserModel();
        $discount = new DiscountModel();

        $p_id = cmf_get_current_user_id();
        $this->checkUserLogin();

        //如果连续生成两次订单，生成第三次的时候先去支付或者取消订单
        $order_count = $order_model->where(['parent_id' => $p_id, 'order_status' => 0])->count();
        if ($order_count > 1) {
            $this->error('你还有没有支付的订单呢');
        }
        //家长的学生信息
        $student_data = $student_model->where(['u_id' => $p_id])->select();
        $count=$student_data->count();
        //没有学生信息，去填写学生信息
        if (empty($count)) {
            $this->redirect('order/add_student', array('id' => $class_id));
        } else {
            $student_data = $student_data->toArray();
        }
        $data= $class_model->where('id', $class_id)->find();
        $course_id = $class_model->where('id', $class_id)->value('course_id');
        $unit_price = $course_model->where('id', $course_id)->value('unit_price');
        //chase添加查询座位信息;
        //$cid应为传输过来的班级id;
        //查询班级对应教室,家长座位,过道,排列;
        $seat_data = $class_model->alias('c')->where('c.id', $class_id)
            ->field('c.classroom_id,cr.rows,cr.cols,cr.aisle,cr.vip,cr.student_nums')
            ->join('classroom cr', 'cr.id=c.classroom_id')
            ->select()
            ->toArray();
        if (!empty($seat_data[0]['aisle'])) {
            $seat_data[0]['aisle'] = unserialize($seat_data[0]['aisle']);
        }
        if (!empty($seat_data[0]['vip'])) {
            $seat_data[0]['vip'] = unserialize($seat_data[0]['vip']);
        }
        $seat_data[0]['student_seat'] = '';

        //查询班级中保留座位和学生已选座位
        $class_seat_model = new ClassSeatModel();
        $class_seat_data = $class_seat_model->alias('cs')
            ->field('cs.student_seat,cs.reserved_seats')
            ->where('classes_id', $class_id)
            ->where('delete_time',0)
            ->select()
            ->toArray();

        foreach ($class_seat_data as &$x) {
            if (!empty($x['student_seat'])) {
                $seat_data[0]['student_seat'] = $seat_data[0]['student_seat'] . unserialize($x['student_seat']) . ",";
            }
            if (!empty($x['reserved_seats'])) {
                $seat_data[0]['reserved_seats'] = unserialize($x['reserved_seats']);
            }
        }

        if (empty($seat_data[0]['student_seat'])) {
            $seat_data[0]['student_seat'] = '';
        }
        if (empty($seat_data[0]['reserved_seats'])) {
            $seat_data[0]['reserved_seats'] = '';
        }


        $this->assign('seat_data', $seat_data);
        $this->assign('student_data', $student_data);
        $this->assign('unit_price', $unit_price);
        $this->assign('data', $data);
        $this->assign('student_status', $student_status);



        //chase添加查询座位信息end;
        return $this->fetch();

    }
    public function one_order()
    {
        //非法登录操作
        $this->checkUserLogin();
        if ($this->request->isPost()) {
            $p_id = cmf_get_current_user_id();
            $param=$this->request->post();
            $course_model = new CourseModel(); //课程
            $order_model = new OrderModel();  //order订单表
            $class_model = new ClassModel();  //班级表
            $class_seat_model = new ClassSeatModel(); //坐位表
            $class_student_model=new ClassStudentModel(); //class_student
            $audition_model=new AuditionModel();//试听表

            $post = $this->request->post();
            $class_id = $post['class_id'];       //班级id
            $student_id = $post['student_id'];
            $cha_id = $this->request->param('cha_id', '0');     //是否插板

            //判断学生是否在此班级占座了
            $class_seat_model = new ClassSeatModel();
            $student_seat = $class_seat_model->where(['classes_id' => $class_id, 'student_id' => $student_id, 'delete_time' => 0])->find();
            if (!empty($student_seat)) {
                $this->error('您在此班级已经报过名了!!!');
            }
            if (empty($student_id)) {
                //选择学生为空
                $this->error('请选择孩子');
            }
            if (empty($post['student_seat'])) {
                $this->error('请至少选择一个座位');
            }
            //注意并发性
            $file = fopen(__DIR__ . '/2.html.lock', "w+");

            // 排它性的锁定
            if (flock($file, LOCK_EX)) {
                fwrite($file, "Write something");
                $count = $class_seat_model->where(['classes_id' => $class_id, 'student_seat' => $student_seat])->find();

                if (!is_null($count)) {
                    flock($file, LOCK_UN);
                    $this->error('座位已经占了');
                }
                // release lock
                flock($file, LOCK_UN);
            } else {
                echo "Error locking file!";
            }





            $class_data= $class_model->where('id', $class_id)->find();
            $school_id=$class_data['school_id'];
            $course_id =$class_data['course_id'];
            $unit_price = $course_model->where('id', $course_id)->value('unit_price');



            //查看课时             //排课表
            $lesson_schema=Db::name('course_schedule')->where(['class_id'=>$class_id])->order('date','asc')->select();
            if($lesson_schema->isEmpty())
            { //课时为空的情况
                $this->error('课时情况正在调整');
            }
            $lesson_schema = $lesson_schema->toArray(); //转化数据
            sortArrByField($lesson_schema,'date',$asc = true); //时间排序（防止加课）正序
            $last=count($lesson_schema); //取得最后一个课时日期
            if (empty($lesson_schema[0]['date'])) {
                //排课表第一节课为空
                $this->error('第一节课不存在');
            }
            //插板过来的学生 ，算课时
            $cur_time = time();
            foreach ($lesson_schema as $k => $v) { //找出课时
                if (!empty($lesson_schema[$k + 1]['date'])) { //一般都是存在的2课时以上的
                    if ($cur_time > $lesson_schema[$k]['date'] && $cur_time < $lesson_schema[$k + 1]['date']) {
                        $progress = $lesson_schema[$k]['schedule']; //当前课时
                        $date = $lesson_schema[$k]['date']; //当前日期
                        $week = $lesson_schema[$k]['week']; //当前周几
                        $start_time = $lesson_schema[$k]['start_time']; //开始时间
                        $end_time = $lesson_schema[$k]['end_time']; //结束时间

                    } elseif ($cur_time < $lesson_schema[0]['date']) { //小于开课时间
                        $progress = 0;
                        $date = $lesson_schema[$k]['date']; //当前日期
                        $week = $lesson_schema[$k]['week']; //当前周几
                        $start_time = $lesson_schema[$k]['start_time']; //开始时间
                        $end_time = $lesson_schema[$k]['end_time']; //结束时间
                    } else if ($cur_time > $lesson_schema[$last - 1]['date']) {  //已经结课
                        $progress = $last; //剩余课时
                        $date = $lesson_schema[$k]['date']; //当前日期
                        $week = $lesson_schema[$k]['week']; //当前周几
                        $start_time = $lesson_schema[$k]['start_time']; //开始时间
                        $end_time = $lesson_schema[$k]['end_time']; //结束时间
                    }
                }

            }
                $student_seat = []; //class_student
                $data_seat = [];  //class_seat
                $data = [];   //order
                $data_audition = [];   //audition


                $data = [];
                $data['amount'] = $unit_price;


                $data_student['insert_class_time'] = time();
                $data_student['course_id'] = $course_id;
                $data_student['class_id'] = $class_id;
                $data_student['student_id'] = $student_id;


                $student_seat = serialize($param['student_seat']);
                $data_seat['student_seat'] = $student_seat;
                $data_seat['classes_id'] = $class_id;
                $data_seat['student_id'] = $student_id;
                $data_seat['create_time'] = time();


                $data_audition['schedule'] = $progress;
                $data_audition['start_time'] = $start_time;
                $data_audition['end_time'] = $end_time;
                $data_audition['date'] = $date;
                $data_audition['course_id'] = $course_id;
                $data_audition['student_id'] = $student_id;
                $data_audition['school_id'] = $school_id;
                $data_audition['class_id'] = $class_id;
                $data_audition['parent_id'] = $p_id;
                $data_audition['money'] = $unit_price;
				$data_audition['create_time'] = time();
                Db::startTrans();
                try {
                    //order
                    $data['parent_id'] = $p_id;
                    $data['order_id'] = $order_model->generate_code();
                    $data['student_id'] = $student_id;
                    $data['class_id'] = $class_id;
                    $data['discount_amout'] = 0;
                    $data['pay_amount'] = $data['amount'];
                    $data['create_time'] = time();
                    $data['cancel_time'] = time() + config('order_expire_time');

                    $insert_id = $order_model->insertGetId($data);//订单表
                    $order_id = $order_model->where('id', $insert_id)->value('order_id');

                    $class_seat_model->insert($data_seat); //座位表
                    $class_student_model->insert($data_student); //class_student
                    //试听表
                    $data_audition['order_id'] = $insert_id;


                    $audition_model->insert($data_audition); //试听表

                    $count = $class_student_model->where(['class_id' => $class_id])->count();
                    $class_model->where(['id' => $class_id])->update(['current_num' => $count]);
                    Db::commit();
                    $this->success('选座成功', url('order/FrontOrder/orderPay', array('order_id' => base64_encode($order_id), 'student_id' => $student_id)));
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error('选座失败');
                    }
            }
       }
    public function select_seat()
    {
        $class_seat_model = new ClassSeatModel(); //坐位表
        $class_student_model=new ClassStudentModel(); //class_student
        $class_model = new ClassModel();  //班级表
        $param=$this->request->post();
        $post=$this->request->post();
        if(!empty($_SESSION['old_class_id']))
        {
                $old_class_id=$_SESSION['old_class_id'];
        }
        if (empty($post['student_seat'])) {
            $this->error('请至少选择一个座位');
        }
        $class_id = $param['classes_id'];       //班级id
        $student_id = $param['student_id'];
    ;
        $data_seat=[];//class_seat
        $student_seat = serialize($param['student_seat']);
        $data_seat['student_seat']= $student_seat;
        $data_seat['classes_id']= $class_id;
        $data_seat['student_id']= $student_id;
        $data_seat['create_time']= time();
        Db::startTrans();
        try {
        //判断学生是否在此班级占座了
        $student_seat = $class_seat_model->where(['classes_id' => $class_id, 'student_id' => $student_id, 'delete_time' => 0])->find();
        if (!empty($student_seat)) {
            $this->error('您在此班级已经报过名了!!!');
        }

        //注意并发性
        $file = fopen(__DIR__ . '/2.html.lock', "w+");

        // 排它性的锁定
        if (flock($file, LOCK_EX)) {
            fwrite($file, "Write something");
            $count = $class_seat_model->where(['classes_id' => $class_id, 'student_seat' => $student_seat])->find();

            if (!is_null($count)) {
                flock($file, LOCK_UN);
                $this->error('座位已经占了');
            }
            // release lock
            flock($file, LOCK_UN);
        } else {
            echo "Error locking file!";
        }

            $count = $class_student_model->where(['class_id' => $class_id])->count();
            $class_model->where(['id' => $class_id])->update(['current_num' => $count]);
            $class_student_model->where(['old_class_id' => $old_class_id,'student_id'=>$student_id])->update(['class_id' => $class_id]);

            $class_student_model->where(['class_id' => $class_id,'student_id'=>$student_id])->update(['status' => 0]);
            $class_seat_model->insert($data_seat);
            $current_num = $class_student_model->where(['class_id' => $class_id])
                ->where(['delete_time'=>0])->count();
            Db::name('class')->where(['id' => $class_id])->update(['update_time' => time(), 'current_num' => $current_num]);
             Db::commit();
            $this->success('选座成功',url('jiaxiaotong/jiaxiaotong/index'));
            }
        catch (Exception $e) {
            $this->error('选座失败');
            Db::rollback();
        }
    }
}